<template>
  <div class="page-mobile-course-combo">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      :title="title"
    ></white-header>
    <div class="combo-list">
      <combo-card
        v-for="(item, index) in course_combo_list"
        :key="index"
        :detail="item"
        :bottomInline="index != course_combo_list.length - 1"
      ></combo-card>
      <div class="footer" v-show="course_combo_list.length != 0">
        <span class="tips">我是有底线的</span>
      </div>
      <van-empty description="暂无套餐" v-if="course_combo_list.length == 0" />
    </div>
  </div>
</template>

<script>
import ComboCard from "~/components/mobile/ComboCard.vue";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import { mapState, mapActions, mapMutations } from "vuex";
import { getMemberInfo, getMember } from "~/api/member";
import { getCourseComboList } from "~/api/course-combo";
export default {
  props: ["setDisabled", "refreshFun", "setLoading"],
  components: {
    ComboCard,
    WhiteHeader
  },
  data() {
    return {
      page: 1,
      pageSize: 10,
      total: 0,
      course_combo_list: [],
      scroll_heigth: 0,
      title: "课程套餐"
    };
  },
  computed: {
    ...mapState({
      token(state) {
        return state.token;
      },
      user_info(state) {
        return state.user_info;
      },
      is_loading(state) {
        return state.is_loading;
      },
      is_member(state) {
        return JSON.stringify(state.member_info) != "{}";
      },
      user_member(state) {
        return state.member_info;
      }
    })
  },
  watch: {},
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    ...mapActions(["initMember"]),
    async getMemberInfo() {
      this.SET_IS_LOADING(true);
      if (this.token && Object.keys(this.user_info).length > 0) {
        let memberDiscount = await getMemberInfo(this.user_info.id);
        if (
          memberDiscount &&
          memberDiscount.data &&
          memberDiscount.data.code == 200
        ) {
          this.memberDiscount = memberDiscount.data.data;
        } else {
          
        }
      }

      this.SET_IS_LOADING(false);
    },
    async getData(fetch_type) {
      return new Promise(async (resolve, reject) => {
        this.SET_IS_LOADING(true);
        let params = {
          offset: this.pageSize * (this.page - 1),
          limit: this.pageSize,
          sort: "id desc"
        };
        let result = await getCourseComboList(params);
        if (result && result.data && result.data.code == 200) {
          this.SET_IS_LOADING(false);
          this.total = result.data.data.total;
          if (fetch_type == "pullup") {
            this.course_combo_list = [
              ...this.course_combo_list,
              ...result.data.data.rows
            ];
          } else {
            this.course_combo_list = result.data.data.rows;
          }
        } else {
          this.SET_IS_LOADING(false);
          this.$toast(
            this.$t("locale.mobile.index.t9"),
            result && result.data && result.data.msg
          );
        }
      })
        .then()
        .catch(e => {
          this.SET_IS_LOADING(false);
        });
    },
    initPage() {
      return new Promise((res, rej) => {
        if (process.client) {
          try {
            this.getData();
            this.getMemberInfo();
            this.initMember();
            res("success");
          } catch (e) {
            console.log(e);
            rej(e);
          }
        }
      }).then();
    },
    throttle(fn, delay) {
      let lastTime = 0;
      return !(function() {
        let nowTime = Date.now();
        if (nowTime - lastTime > delay) {
          fn.call(this);
          lastTime = nowTime;
        }
      })();
    },
    pullUp() {
      // 滚动条离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 窗口可视区域高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      // 滚动区域高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      if (scrollTop + clientHeight >= scrollHeight - 120) {
        console.log("上拉加载");
        if (this.total <= this.course_combo_list.length) {
          return;
        }
        if (this.is_loading) {
          return;
        }
        this.page++;
        this.getData("pullup");
      }
    },
    eventListener() {
      this.throttle(this.pullUp, 30);
    },
    initState() {
      this.page = 1;
      this.pageSize = 10;
      this.total = 0;
    }
  },
  activated() {
    if (process.client) {
      this.$nextTick(() => {
        setTimeout(() => {
          document.body.scrollTop = this.scroll_heigth;
          document.documentElement.scrollTop = this.scroll_heigth;
        }, 0);
      });
      window.addEventListener("scroll", this.eventListener);
      this.initPage();
    }
    this.setDisabled(false);
    this.refreshFun(() => {
      this.initPage()
        .then(res => {
          if (res == "success") {
            this.setLoading(false);
          }
        })
        .catch(() => {
          this.setLoading(false);
          this.SET_IS_LOADING(false);
        });
    });
  },
  deactivated() {
    let scroll_heigth =
      document.documentElement.scrollTop || document.body.scrollTop;
    this.scroll_heigth = scroll_heigth;
    this.initState();
    this.setDisabled(true);
    window.removeEventListener("scroll", this.eventListener);
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.eventListener);
  },
  created() {
    //开启下拉刷新
    this.setDisabled(false);
    //初始化页面数据
    this.initPage();
    //下拉回调
    this.refreshFun(() => {
      this.initPage()
        .then(res => {
          if (res == "success") {
            this.setLoading(false);
          }
        })
        .catch(() => {
          this.setLoading(false);
          this.SET_IS_LOADING(false);
        });
    });
    //返回上次页面滚动条的位置
    // this.$nextTick(() => {
    //   document.body.scrollTop = this.scroll_heigth;
    //   document.documentElement.scrollTop = this.scroll_heigth;
    // });
  },
  mounted() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
  }
};
</script>

<style lang="scss" scoped>
.page-mobile-course-combo {
  min-height: calc(100vh - 1.6rem);
  .footer {
    padding: 0.3rem;
    font-size: 0.26rem;
    color: #babec2;
    text-align: center;
    .tips {
      position: relative;
    }
    .tips::before {
      content: "";
      display: block;
      position: absolute;
      left: -1.7rem;
      top: 50%;
      transform: translateY(-1px);
      width: 1.5rem;
      height: 1px;
      background: #babec2;
    }
    .tips::after {
      content: "";
      display: block;
      position: absolute;
      right: -1.7rem;
      top: 50%;
      width: 1.5rem;
      transform: translateY(-1px);
      height: 1px;
      background: #babec2;
    }
  }
  .combo-list {
    border-top: 1px solid #ededf1;
  }
}
</style>
<style lang="scss">
.page-mobile-course-combo {
}
</style>
